package com.nec.recommend.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nec.recommend.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
public class RequestUtil {
    public static JSONObject get(String url, Object params) {
        return get(url, params, null);
    }

    public static JSONObject get(String url, Object params, JSONObject headers) {
        OkHttpClient okHttpClient = new OkHttpClient();
        JSONObject jsonObject = JSONUtil.parseObj(params);
        String paramsStr = jsonObject.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&"));
        try {
            url = url + "?" + paramsStr;
            Request.Builder builder = new Request.Builder().url(url).get();
            //增加请求头
            if (Objects.nonNull(headers)) {
                headers.forEach((key, value) -> builder.addHeader(key, value.toString()));
            }
            final Request request = builder.build();
            log.info("okHttp Get请求地址：{}", url);
            Response response = okHttpClient.newCall(request).execute();
            ResponseBody body = response.body();
            if (Objects.nonNull(body)) {
                String string = body.string();
                return JSONUtil.parseObj(string);
            }
        } catch (IOException e) {
            log.error("okHttp请求出现错误，", e);
        }
        throw new ServiceException("okHttp请求出现错误");
    }

    public static JSONObject post(String url, Object data) {
        return post(url, data, null);
    }

    public static JSONObject post(String url, Object data, JSONObject headers) {
        return post(url, data, headers, null);
    }

    public static JSONObject post(String url, Object data, JSONObject headers, Object params) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        if (Objects.nonNull(params)) {
            JSONObject jsonObject = JSONUtil.parseObj(params);
            url += "?" + jsonObject.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&"));
        }
        String requestBody;
        if (Objects.isNull(data)) {
            requestBody = "{}";
        } else {
            requestBody = JSONUtil.toJsonStr(data);
        }
        try {
            Request.Builder requestbuilder = new Request.Builder().url(url).post(RequestBody.create(mediaType, requestBody));
            //增加请求头
            if (Objects.nonNull(headers)) {
                headers.forEach((key, value) -> requestbuilder.addHeader(key, value.toString()));
            }
            log.info("okHttp Post请求地址：{}", url);
            Request request = requestbuilder.build();
            OkHttpClient okHttpClient = new OkHttpClient();
            Response response = okHttpClient.newCall(request).execute();
            ResponseBody body = response.body();
            if (Objects.nonNull(body)) {
                String string = body.string();
                JSONObject jsonObject = JSONUtil.parseObj(string);
                if (jsonObject.getInt("errcode") != 0) {
                    throw new ServiceException("okHttp Post请求出现错误：" + string);
                }
                return jsonObject;
            }
        } catch (IOException e) {
            log.error("okHttp请求出现错误，", e);
        }
        throw new ServiceException("okHttp请求出现错误");
    }
}
